package com.example.controller;

import com.example.common.Result;
import com.example.common.UploadResult;
import com.example.controller.params.D01UploadDeviceDataParam;
import com.example.model.MachineTx;
import com.example.model.OperationLedger;
import com.example.service.MachineService;
import com.example.service.OperationLedgerService;
import com.example.temp.APIGWDemo;
import com.example.utils.JacksonUtil;
import com.example.utils.MachineTestToUploadDataUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.CollectionUtils;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.annotation.Resource;
import java.util.*;
import java.util.stream.Collectors;

@RestController
@RequestMapping("/d01")
public class MachineD01Controller {

    @Autowired
    private BatchQrCodeManager outStockQrCodeManager;
    @Resource
    public MachineService machineService;

    @Autowired
    public OperationLedgerService operationLedgerService;



    @PostMapping("/uploadCCD")
    public Result uploadCCD(@RequestBody D01UploadDeviceDataParam param) {
        System.out.println(param);
        try {
            String batchqrcode = param.getBatchQrcode();
            List<String> qrCodes = outStockQrCodeManager.queryQrCodesByBatchQrcode(batchqrcode);
            Map<String,Integer> qrCounttMap = new HashMap<>();
            List<MachineTx> machineTxList  = machineService.listMachineTxByQrCodes(qrCodes);

            for (MachineTx tx : machineTxList) {
                if(tx.getMachine_test()==null){
                    continue;
                }
                Integer count = qrCounttMap.getOrDefault(tx.getQrcode(), 0);
                qrCounttMap.put(tx.getQrcode(), count + tx.getMachine_test().size());
            }

            System.out.println("qrcode对应数量统计----------->   " + JacksonUtil.bean2Json(qrCounttMap));

            Map<String,MachineTx> machineQrMap = new HashMap<>();
            Map<String,String> deplicateMachineMap = new HashMap<>(); //同一二维码+机器编码进行排重
            for (MachineTx tx : machineTxList) {
                String uniqueKey = tx.getQrcode() +"_"+ tx.getMachine_id(); //唯一键值
                if(tx.getMachine_test()==null || !"OK".equals(tx.getResult()) || deplicateMachineMap.get(uniqueKey)!=null){
                    continue;
                }
                deplicateMachineMap.put(uniqueKey, "exists");
                MachineTx existsTx = machineQrMap.get(tx.getQrcode());
                if(existsTx==null){
                    machineQrMap.put(tx.getQrcode(), tx);
                } else {
                    if(!CollectionUtils.isEmpty(existsTx.getMachine_test())) {
                        existsTx.getMachine_test().addAll(Optional.ofNullable(tx.getMachine_test()).orElse(Collections.emptyList()));
                    } else {
                        existsTx.setMachine_test(tx.getMachine_test());
                    }
                }
            }


            for (Map.Entry<String, MachineTx> entry : machineQrMap.entrySet()) {
                System.out.println("qrcode: " + entry.getKey() + " 原list统计:" + qrCounttMap.get(entry.getKey()) + ", 现合并后数量: " + entry.getValue().getMachine_test().size());
            }

            List<MachineTx> newMachineList = machineQrMap.entrySet().stream().map(Map.Entry::getValue).collect(Collectors.toList());
            //  List<MachineTx> machineTxList  = machineService.listMachineTxByQrCodes(batchqrcode);

            //上传到日志
            OperationLedger ledger = new OperationLedger();
            ledger.setOperationName("Mes_app测量数据上传D01客户");
            ledger.setOperationParameters(batchqrcode);
            ledger.setOperator("OQC扫码");
            ledger.setResult("");
            ledger.setCounts(0);
            // System.out.println(ledger);
            operationLedgerService.insertOperationLedger(ledger);
            //获取带ID的对象
            ledger =  operationLedgerService.selectOperationLedgerByParam(batchqrcode);
            int count = 0;
            for (MachineTx machineTx : newMachineList) {
                String uploadData = MachineTestToUploadDataUtil.convert(batchqrcode,machineTx);
                System.out.println(uploadData);
              //  String json="{\"data\":{\"barCode\":\"ZSF02L2391200317\",\"testResult\":\"OK\"},\"dataType\": \"WPTM\",\"materialType\": \"COVER\"}";
              //  String json="{\"data\":{\"barCode\":\"testxxxxx001\",\"testResult\":\"OK\"},\"dataType\": \"WPTM\",\"materialType\": \"COVER\"}";
                //上传到D01服务器
               // APIGWDemo.getRomteData(json);
              //上传到D01服务器
               APIGWDemo.getRomteData(uploadData);
                   count++;
               // machineTx.getQrcode();
               // batchqrcode;
               ledger.setCounts(count);
               operationLedgerService.updateOperationLedger(ledger);
            }
            ledger.setResult("Success");
            operationLedgerService.updateOperationLedger(ledger);
                /*
                //上传到日志
                OperationLedger ledger = new OperationLedger();
                ledger.setOperationName("Mes_app测量数据上传D01客户");
                ledger.setOperationParameters(batchqrcode);
                ledger.setOperator("OQC扫码");
                ledger.setResult("Success");
               // System.out.println(ledger);
                operationLedgerService.insertOperationLedger(ledger);
*/
            return Result.ok(batchqrcode);

           // return Result.data(machineTxList);
        } catch (Exception e) {
            throw new RuntimeException(e);

        }
    }

}
